﻿
#region Usings
using System;
using System.Collections.Generic;

#endregion

namespace OF.Utility
{
    /// <summary>
    /// 泛型参数排序 实现类
    /// </summary>
    /// <typeparam name="T">引用类类型</typeparam>
    public class GenericComparer<T> : IComparer<T> where T : IComparable
    {
        #region Functions
        /// <summary>
        /// 接口方法实现
        /// </summary>
        /// <param name="x">参数 x</param>
        /// <param name="y">参数 y</param>
        /// <returns>当返回一个大于0的int时，即(x>y).返回一个小于0的int时即(x小于y).当返回0时即表示(x==y)</returns>
        public int Compare(T x, T y)
        {
            if (!typeof(T).IsValueType
                || (typeof(T).IsGenericType
                && typeof(T).GetGenericTypeDefinition().IsAssignableFrom(typeof(Nullable<>))))
            {
                if (Object.Equals(x, default(T)))
                    return Object.Equals(y, default(T)) ? 0 : -1;
                if (Object.Equals(y, default(T)))
                    return -1;
            }
            if (x.GetType() != y.GetType())
                return -1;
            if (x is IComparable<T>)
                return ((IComparable<T>)x).CompareTo(y);
            return x.CompareTo(y);
        }

        #endregion
    }
}